﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Configuration;
using NLog;

namespace Bingosoft.Swimming.Core.Helper
{
    public static class SmsHelper
    {
        static WebClient client;
        static SmsConfig config;
        static SmsHelper()
        {
            client = new WebClient();
            config = SmsConfig.GetInstance();
        }

        public static bool Send(string mobile, string content)
        {
            string postString = "apitype=2&smsname={0}&smspwd={1}&mobile={2}&content={3}";
            postString = string.Format(postString, 
                config.SmsUserName, config.SmsPassword, mobile, content);

            Encoding encode = Encoding.GetEncoding("gb2312");

            byte[] postData = encode.GetBytes(postString);

            client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            client.Headers.Add("ContentLength", postData.Length.ToString());

            byte[] responseData = client.UploadData(config.SmsAPI, "POST", postData);

            try
            {
                string retVal = encode.GetString(responseData);
                
                LogManager.GetCurrentClassLogger().Trace("发短信{0}成功，返回值{1}", mobile, retVal);

                return (!string.IsNullOrEmpty(retVal) && retVal.Split('|')[0] == "1");
            }
            catch (Exception ex)
            {
                LogManager.GetCurrentClassLogger().ErrorException("发短信错误", ex);

                return false;
            }
        }
    }

        public class SmsConfig : ConfigurationSection
    {
        public const string Sms_API = "SmsAPI";
        public const string Sms_User_Name = "SmsUserName";
        public const string Sms_Password = "SmsPassword";

        public static SmsConfig GetInstance()
        {
            SmsConfig config = ConfigurationManager.GetSection("SmsConfig") as SmsConfig;
            return config;
        }

        [ConfigurationProperty(Sms_API, IsRequired = true)]
        public string SmsAPI
        {
            get
            {
                return this[Sms_API] as string;
            }
        }

        [ConfigurationProperty(Sms_User_Name, IsRequired = true)]
        public string SmsUserName
        {
            get
            {
                return this[Sms_User_Name] as string;
            }
        }

        [ConfigurationProperty(Sms_Password, IsRequired = true)]
        public string SmsPassword
        {
            get
            {
                return this[Sms_Password] as string;
            }
        }

    }

}
